package com.espirit.finance.core;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.espirit.eap.util.BigDecimalUtil;
import com.espirit.eap.util.Functions;
import com.googlecode.cswish.util.FreemarkerTplEngine;
import com.googlecode.cswish.util.InvocationUtil;

@Service
public class CalcAcctFixedStrategy implements IAcctCalcStrategy{
	@Resource
	InvocationUtil invocationUtil;
	
	@Resource
	private Functions functions;
	
	@Resource
	AcctItemCalcService acctItemCalcService;
	
	@Override
	public BigDecimal getAmount(TicketAware ticketAware,
			AcctItem acctItem) {
		BigDecimal value = null;
		if (acctItem.getFixedAmount() != null){
			value = acctItem.getFixedAmount();
		} else {
			value = getConditionAmount(acctItem.getConditionAmount(), ticketAware);
		}
		value = acctItemCalcService.getFactorAmount(acctItem, ticketAware, value);
		return value;
	}
	
	public BigDecimal getConditionAmount(String conditionAmount, TicketAware model) {
		if (conditionAmount == null || conditionAmount.isEmpty()){
			return null;
		} else {
//			String condtion = conditionAmount.replaceAll(" > ", " gt ");
//			condtion = condtion.replaceAll(" > ", " gt ");
//			condtion = condtion.replaceAll(" < ", " lt ");
//			condtion = condtion.replaceAll(" >= ", " gte ");
//			condtion = condtion.replaceAll(" <= ", " lte ");
//			condtion = condtion.replaceAll(" and ", " && ");
//			condtion = condtion.replaceAll(" or ", " || ");
			
			Map<String, Object> parameters = new HashMap<String, Object>();
			invocationUtil.forceLoadModelAndResults(parameters);
			parameters.put("fn", functions);
			parameters.put("model", model);
//			parameters.put("action", new MapContext(action));
			
			Map<String, Object> traceResult = new HashMap<String, Object>(4);
			traceResult.put("result", null);

//			System.out.println(conditionAmount);
			FreemarkerTplEngine.getInstance().execute(conditionAmount, parameters, traceResult);
			Object result = traceResult.get("result");
			if (result != null){
				return BigDecimalUtil.getBigDecimalValue(result);
			} else {
				return null;
			}
		}
	}
}
